package com.itxiuyixiu.homework.utils.converter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterRegistry;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * @author 黄磊
 * @date 2020/1/23
 */
@Component
public class String2DateConverter implements Converter<String , Date> {
    @Autowired
    private ConverterRegistry converterRegistry;

    @Bean
    public void addString2DateConverter() {
        converterRegistry.addConverter(new String2DateConverter());
    }

    @Override
    public Date convert(String s) {
        Date date;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        format.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        try {
            date = format.parse(s);
        } catch (Exception e) {
            return null;
        }
        return date;
    }
}
